const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const router = express.Router();
const ExposurePrisma = require('../models/ExposurePrisma');
const ResponseHelper = require('../utils/response');
const { authenticateToken } = require('../middleware/auth');

// 配置multer用于图片上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadDir = 'uploads/exposure/';
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, 'exposure-' + uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({ 
  storage: storage,
  limits: {
    fileSize: 5 * 1024 * 1024, // 5MB
  },
  fileFilter: (req, file, cb) => {
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    if (allowedTypes.includes(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error('只支持图片格式文件'), false);
    }
  }
});

// 图片上传接口
router.post('/upload', authenticateToken, upload.array('images', 9), async (req, res) => {
  try {
    if (!req.files || req.files.length === 0) {
      return ResponseHelper.error(res, '请选择要上传的图片', 400);
    }

    const imageUrls = req.files.map(file => `/${file.path}`);
    ResponseHelper.success(res, { images: imageUrls }, '图片上传成功');
  } catch (error) {
    console.error('图片上传失败:', error);
    ResponseHelper.serverError(res, '图片上传失败', error);
  }
});

// 发布曝光帖子
router.post('/posts', authenticateToken, async (req, res) => {
  try {
    const { content, images } = req.body;
    const userId = req.user.id;

    if (!content || content.trim().length === 0) {
      return ResponseHelper.error(res, '曝光内容不能为空', 400);
    }

    if (content.length > 2000) {
      return ResponseHelper.error(res, '曝光内容不能超过2000字', 400);
    }

    if (images && images.length > 9) {
      return ResponseHelper.error(res, '最多只能上传9张图片', 400);
    }

    const post = await ExposurePrisma.createPost({
      user_id: userId,
      content: content.trim(),
      images: images || []
    });

    ResponseHelper.success(res, { post }, '曝光发布成功');
  } catch (error) {
    console.error('发布曝光失败:', error);
    ResponseHelper.serverError(res, '发布曝光失败', error);
  }
});

// 获取曝光帖子列表
router.get('/posts', async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const pageSize = Math.min(parseInt(req.query.pageSize) || 10, 50); // 最大50条
    
    const result = await ExposurePrisma.getPostsList(page, pageSize);
    
    // 如果用户已登录，检查点赞状态
    if (req.user && req.user.id) {
      for (let post of result.posts) {
        post.is_liked = await ExposurePrisma.checkUserLiked(post.id, req.user.id);
      }
    }

    ResponseHelper.success(res, result, '获取曝光列表成功');
  } catch (error) {
    console.error('获取曝光列表失败:', error);
    ResponseHelper.serverError(res, '获取曝光列表失败', error);
  }
});

// 获取单个帖子详情
router.get('/posts/:id', async (req, res) => {
  try {
    const postId = req.params.id;
    const post = await ExposurePrisma.getPostById(postId);
    
    if (!post) {
      return ResponseHelper.notFound(res, '帖子不存在');
    }

    // 如果用户已登录，检查点赞状态
    if (req.user && req.user.id) {
      post.is_liked = await ExposurePrisma.checkUserLiked(postId, req.user.id);
    }

    ResponseHelper.success(res, { post }, '获取帖子详情成功');
  } catch (error) {
    console.error('获取帖子详情失败:', error);
    ResponseHelper.serverError(res, '获取帖子详情失败', error);
  }
});

// 点赞/取消点赞
router.post('/posts/:id/like', authenticateToken, async (req, res) => {
  try {
    const postId = req.params.id;
    const userId = req.user.id;

    const post = await ExposurePrisma.getPostById(postId);
    if (!post) {
      return ResponseHelper.notFound(res, '帖子不存在');
    }

    const result = await ExposurePrisma.toggleLike(postId, userId);
    ResponseHelper.success(res, result, result.liked ? '点赞成功' : '取消点赞成功');
  } catch (error) {
    console.error('点赞操作失败:', error);
    ResponseHelper.serverError(res, '点赞操作失败', error);
  }
});

// 发表评论
router.post('/posts/:id/comments', authenticateToken, async (req, res) => {
  try {
    const postId = req.params.id;
    const userId = req.user.id;
    const { content } = req.body;

    if (!content || content.trim().length === 0) {
      return ResponseHelper.error(res, '评论内容不能为空', 400);
    }

    if (content.length > 500) {
      return ResponseHelper.error(res, '评论内容不能超过500字', 400);
    }

    const post = await ExposurePrisma.getPostById(postId);
    if (!post) {
      return ResponseHelper.notFound(res, '帖子不存在');
    }

    const comment = await ExposurePrisma.createComment({
      post_id: postId,
      user_id: userId,
      content: content.trim()
    });

    ResponseHelper.success(res, { comment }, '评论发表成功');
  } catch (error) {
    console.error('发表评论失败:', error);
    ResponseHelper.serverError(res, '发表评论失败', error);
  }
});

// 获取帖子评论列表
router.get('/posts/:id/comments', async (req, res) => {
  try {
    const postId = req.params.id;
    const page = parseInt(req.query.page) || 1;
    const pageSize = Math.min(parseInt(req.query.pageSize) || 20, 50);

    const result = await ExposurePrisma.getCommentsByPostId(postId, page, pageSize);
    ResponseHelper.success(res, result, '获取评论列表成功');
  } catch (error) {
    console.error('获取评论列表失败:', error);
    ResponseHelper.serverError(res, '获取评论列表失败', error);
  }
});

// 获取我发布的帖子
router.get('/my-posts', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const page = parseInt(req.query.page) || 1;
    const pageSize = Math.min(parseInt(req.query.pageSize) || 10, 50);

    const result = await ExposurePrisma.getUserPosts(userId, page, pageSize);
    ResponseHelper.success(res, result, '获取我的曝光成功');
  } catch (error) {
    console.error('获取我的曝光失败:', error);
    ResponseHelper.serverError(res, '获取我的曝光失败', error);
  }
});

// 分享统计
router.post('/posts/:id/share', async (req, res) => {
  try {
    const postId = req.params.id;
    
    const post = await ExposurePrisma.getPostById(postId);
    if (!post) {
      return ResponseHelper.notFound(res, '帖子不存在');
    }

    await ExposurePrisma.incrementShareCount(postId);
    ResponseHelper.success(res, {}, '分享统计已记录');
  } catch (error) {
    console.error('分享统计失败:', error);
    ResponseHelper.serverError(res, '分享统计失败', error);
  }
});

module.exports = router;